<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="80px">
      <el-form-item label="产品编码" prop="modelCode">
        <el-input v-model="queryParams.modelCode" placeholder="请输入产品编码" clearable size="small" style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="model">
        <el-input v-model="queryParams.model" placeholder="请输入产品名称" clearable size="small" style="width: 200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="华为任务令" prop="taskTon">
        <el-input v-model="queryParams.taskTon" placeholder="请输入华为任务令" clearable size="small" style="width: 200px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['set:model:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['set:model:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column label="主键id" prop="id" :show-overflow-tooltip="true" v-if="false"/>
      <el-table-column prop="modelCode" label="产品编码" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-button type="text" @click="showDictData(scope.row)">{{ scope.row.modelCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="华为任务令" prop="taskTon" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" prop="modelDesLocal" :show-overflow-tooltip="true" />
      <el-table-column label="总成零件号" prop="model" :show-overflow-tooltip="true" />
      <el-table-column label="产品描述" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-guide" style="margin-right: 9px"
            @click="handleCustmerSet(scope.row)" v-hasPermi="['set:model:khljh']">客户零件号配置</el-button>
          <el-button size="mini" type="text" icon="el-icon-guide" style="margin-right: 9px"
                     @click="handleCustmerSetBOM(scope.row)">BOM物料配置</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" style="margin-right: 9px"
            @click="handleUpdate(scope.row)" v-hasPermi="['set:model:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['set:model:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改车型配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品代码" prop="modelCode">
              <el-input v-model="form.modelCode" placeholder="请输入产品代码" style="width: 240px" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="颜色代码" prop="colorCode">
              <el-input
                v-model="form.colorCode"
                placeholder="请输入颜色代码"
                style="width: 240px"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="华为任务令" prop="taskTon">
              <el-input v-model="form.taskTon" placeholder="请输入华为任务令" style="width: 240px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="modelDesLocal">
              <el-input v-model="form.modelDesLocal" placeholder="请输入产品名称" style="width: 240px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总成零件号" prop="model" label-width="100px">
              <el-select v-model="form.model" filterable placeholder="请选择总成零件号" style="width: 240px">
                <el-option v-for="item in MESMATERIALOptions" :key="item.materialCode" :label="item.materialCode"
                  :value="item.materialCode">
                  <span style="float: left">{{ item.materialCode }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="车型大类" prop="modelType">
              <el-input
                v-model="form.modelType"
                placeholder="请输入车型大类"
                style="width: 240px"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="产品描述" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入产品描述" style="width: 240px" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="车型分组号" prop="deliveryGroup">
              <el-input
                v-model="form.deliveryGroup"
                placeholder="请输入车型分组号"
                style="width: 240px"
              />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 车型导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的车型数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="关联关重件" :visible.sync="StepsVisible" width="80%" :lock-scroll="false">
      <scan-data :clientId="CarTypeId" :cartypeInfo="CartypeInfo"></scan-data>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listSetModel,
    getSetModel,
    delSetModel,
    addSetModel,
    updateSetModel,
    exportSetModel,
    importTemplate,
    dataScope,
    listAllSetModel,
  } from "@/api/parameter/set_model";
  import { getToken } from "@/utils/auth";
  import scanData from "@/views/components/scanData";
  import { listAllMaterial } from "@/api/base/material";
  export default {
    name: "set_model",
    components: { scanData },
    data() {
      return {
        //物料下拉
        MESMATERIALOptions: [],
        StepsVisible: false,
        CarTypeId: 0,
        CartypeInfo: "",
        // 车型导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/set/model/importData",
        },
        // 遮罩层
        loading: true,
        // 选中数组
        modelCodes: [],
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 角色表格数据
        roleList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          modelCode: undefined,
          model: undefined
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label",
        },
        // 表单校验
        rules: {
          modelCode: [{ required: true, message: "产品编码不能为空", trigger: "blur" }],
          modelDesLocal: [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
          taskTon: [{ required: true, message: "华为任务令不能为空", trigger: "blur" }]
        },
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_normal_disable").then((response) => {
        this.statusOptions = response.data;
      });
      listAllMaterial().then((res) => {
        this.MESMATERIALOptions = res;
      });
    },
    methods: {
      showDictData(row) {
        this.CarTypeId = row.id;
        this.CartypeInfo = row.modelCode;
        this.StepsVisible = true;
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "车型导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        importTemplate().then((response) => {
          this.download(response.msg);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 查询车型列表 */
      getList() {
        this.loading = true;
        listSetModel(this.addDateRange(this.queryParams, this.dateRange)).then(
          (response) => {
            this.roleList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 取消按钮（数据权限）
      cancelDataScope() {
        this.openDataScope = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.modelCodes = selection.map((item) => item.modelCode);
        this.ids = selection.map((item) => item.modelCode);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加产品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        // const modelCodes = row.modelCode || this.modelCodes;
        const id = row.id || this.ids;
        //   const roleMenu = this.getSetModelMenuTreeselect(roleId);
        getSetModel(id).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改产品";
        });
      },
      /** 修改按钮操作 */
      handleCustmerSet(row) {
        const id = row.id;
        const model = row.model;
        this.$router.push(`/set_model/custmer/${id}/${model}`);
      },
      handleCustmerSetBOM(row) {
        const id = row.id;
        const model = row.model;
        this.$router.push(`/set_model/bomData/${id}/${model}`);
      },

      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != undefined) {
              updateSetModel(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addSetModel(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 提交按钮（数据权限） */
      submitDataScope: function () {
        if (this.form.id != undefined) {
          dataScope(this.form).then((response) => {
            if (response.code === 200) {
              this.msgSuccess("修改成功");
              this.openDataScope = false;
              this.getList();
            }
          });
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ModelIds = row.id || this.ids;
        this.$confirm(
          '是否确认删除车型编号为"' + ModelIds + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delSetModel(ModelIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () { });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm("是否确认导出所有车型?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return exportSetModel(queryParams);
          })
          .then((response) => {
            this.download(response.msg);
          })
          .catch(function () { });
      },
    },
  };
</script>
